//
//  HistoryViewModel.swift
//  ShouChong
//
//  Created by yw on 2024/7/22.
//

import Foundation


struct ChartModel:Identifiable {
    var id:String = UUID().uuidString
    var count:Int
//    var calorie:Int
//    var time:Int
    var duration:Int
    var createDate:Date
    var heartRate:Int
}

enum DateType {
    case weekday
    case month
}

extension DateType {
    var value:String {
        switch self {
        case .weekday:
            return "周"
        case .month:
            return "月"
        }
    }
}

class HistoryViewModel:ObservableObject {
    @Published var list:[HistoryModel] = []
    @Published var chartList:[ChartModel] = []
    
    init() {
//        getHistoryList()
        getHistoryWithDateType(dateType: .weekday)
    }
    func getHistoryWithDateType(now:Date = Date(), dateType:DateType) {
        let calendar = Calendar.current
//        let now = Date()
        if dateType == .weekday {
            // 获取当前日期的星期几（1表示星期日，7表示星期六）
            let weekday = calendar.component(.weekday, from: now)
            // 计算星期的第一天（星期日）的日期
            let startOfWeek = calendar.date(byAdding: .day, value: 1 - weekday, to: now)!
            // 计算星期的最后一天（星期六）的日期
            let endOfWeek = calendar.date(byAdding: .day, value: 7 - weekday, to: now)!
            let startDate = String().date2String(startOfWeek,dateFormat: .format_00)
            let endDate = String().date2String(endOfWeek,dateFormat: .format_59)
            getHistoryList(startDate: startDate, endDate: endDate)
        } else if dateType == .month {
            let month = calendar.component(.month, from: now)
            let year = calendar.component(.year, from: now)
            var dateComponents = DateComponents(year: year,month: month)
            guard let firstDay = calendar.date(from: dateComponents) else {
                return
            }
            dateComponents.day = calendar.range(of: .day, in: .month, for: now)?.count
            guard let lastDay = calendar.date(from: dateComponents) else {return}
            let startDate = String().date2String(firstDay,dateFormat: .format_00)
            let endDate = String().date2String(lastDay,dateFormat: .format_59)
            getHistoryList(startDate: startDate, endDate: endDate)
        }
    }
    
    func getHistoryList(startDate:String = "",endDate:String = "") {
        
        let sendData = [
            "startDate":startDate,
            "endDate":endDate
        ]
        DPrint("获取时间范围：\(sendData)")
        YWNetworkTool.share().requestJson(url: "info/getNNHistory", parameters: sendData) { res in
            DPrint(res)
            guard let results = res as? [String:Any],
                  let data = results["data"] as? [[String:Any]],
                  let jsonData = try? JSONSerialization.data(withJSONObject: data) else {
                YWToast.show(text: "获取列表失败")
                return
            }
            do {
                let models = try JSONDecoder().decode([HistoryModel].self,from: jsonData)
                self.list = models
                self.chartList = self.list.map({ item in
//                    let startDate = item.startTime.string2Date(item.startTime, dateFormat: .format_default)
//                    let endDate = item.startTime.string2Date(item.endTime, dateFormat: .format_default)
//                    let components = Calendar.current.dateComponents([.second], from: startDate, to: endDate)
                    return ChartModel(
                        count: Int(item.count) ?? 0,
//                        calorie: Int(item.calorie) ?? 0,
//                        time:components.second ?? 0,
                        duration: Int(item.duration) ?? 0, 
                        createDate:String().string2Date(item.createTime),
                        heartRate: Int(Double(item.heartRate) ?? 0.0)
                    )
                })
            } catch {
                YWToast.show(text: "数据解析失败\(error.localizedDescription)")
            }
        } responseFailBlock: { error, code in
            DPrint(error)
            YWToast.show(text: "获取列表失败")
            
        }
    }
    
    
    func getHisByPage(sendData:[String:String],successBlock:@escaping (_:[HistoryModel]) -> Void) {
        YWNetworkTool.share().requestJson(url: "info/getNNHistoryByPage", parameters: sendData) { res in
            DPrint(res)
            guard let results = res as? [String:Any],
                  let data = results["data"] as? [[String:Any]],
                  let jsonData = try? JSONSerialization.data(withJSONObject: data) else {
                YWToast.show(text: "获取列表失败")
                return
            }
            do {
                let models = try JSONDecoder().decode([HistoryModel].self,from: jsonData)
                successBlock(models)
            } catch {
                YWToast.show(text: "数据解析失败\(error.localizedDescription)")
            }
        } responseFailBlock: { error, code in
            DPrint(error)
            YWToast.show(text: "获取列表失败")
            
        }
    }
    
   
}
